5.1 Insertion:

You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.


In [26]:
bit = 0xFFFF

M = 0x5
N = 0xF00F

def insertion(M, N, i, j):
    ALL = 0xFFFFFFFF
    left_mask = ALL << j + 1
    print(bin(ALL))
    print("left_mask:" + bin(left_mask))
    right_mask = ALL >> (32 - i)
    
    mask = left_mask|right_mask
    print(bin(mask))
    
    M_ = (M << i)
    ret = (N&mask) | M_
    
    print(bin(M_))
    print(bin(ret))


    return ret

print(bin(insertion(M, N, 3, 5)))


0b11111111111111111111111111111111
left_mask:0b11111111111111111111111111111111000000
0b11111111111111111111111111111111000111
0b101000
0b1111000000101111
0b1111000000101111

5.2 Binary to String:

Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print"ERROR:'


In [46]:
def bin_to_str(number):
    
    strs = []
    remain = number
    for i in range(1, 31):
        if remain == 0:
            break
        elif remain - 0.5**i >= 0:
            remain = remain - 0.5**i
            strs.append(str(1))
        else:
            strs.append(str(0))
            
        print(remain, 0.5**i)
        
    
    if remain > 0:
        return "ERROR"
    else:
        return "0." + "".join(strs)

print(bin_to_str(0.875))


0.375 0.5
0.125 0.25
0.0 0.125
0.111

In [ ]: